package cn.com.czpb.client.module.personal.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.StyleRes;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import cn.com.czpb.client.R;
import cn.com.czpb.client.custorm.picker.OnWheelChangedListener;
import cn.com.czpb.client.custorm.picker.WheelView;
import cn.com.czpb.client.custorm.picker.adapters.ArrayWheelAdapter;
import cn.com.czpb.client.model.event.ChangeLocationEvent;
import cn.com.czpb.client.model.usercenter.CityModel;
import cn.com.czpb.client.model.usercenter.DistrictModel;
import cn.com.czpb.client.model.usercenter.ProvinceModel;
import cn.com.czpb.client.model.usercenter.UserEntity;
import cn.com.czpb.client.module.personal.service.XmlParserHandler;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.ParamUtils;
import cn.com.czpb.client.utils.SPUtil;
import cn.com.czpb.client.utils.TUtils;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import butterknife.BindView;
import de.greenrobot.event.EventBus;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/7/31.
 */

public class ChangeLocationDialog extends Dialog implements View.OnClickListener ,OnWheelChangedListener {
    /**
     * 所有省
     */
    protected String[] mProvinceDatas;
    /**
     * key - 省 value - 市
     */
    protected Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
    /**
     * key - 市 values - 区
     */
    protected Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();

    /**
     * key - 区 values - 邮编
     */
    protected Map<String, String> mZipcodeDatasMap = new HashMap<String, String>();

    /**
     * 当前省的名称
     */
    protected String mCurrentProviceName;
    /**
     * 当前市的名称
     */
    protected String mCurrentCityName;
    /**
     * 当前区的名称
     */
    protected String mCurrentDistrictName ="";

    /**
     * 当前区的邮政编码
     */
    protected String mCurrentZipCode ="";

    /**
     * 解析省市区的XML数据
     */


    @BindView(R.id.id_province)
    WheelView mViewProvince;
    @BindView(R.id.id_city)
    WheelView mViewCity;
    @BindView(R.id.id_district)
    WheelView mViewDistrict;
    TextView tv_cancle,tv_ok;
    private View view;
    private SPUtil spu;
    private Activity activity;

    public ChangeLocationDialog(@NonNull Context context) {
        super(context);
        activity = (Activity) context;
        spu = SPUtil.getInstance();

    }

    public ChangeLocationDialog(@NonNull Context context, @StyleRes int themeResId) {
        super(context, themeResId);
        activity = (Activity) context;
        spu = SPUtil.getInstance();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initProvinceDatas();
        init();
        setUpListener();
        setUpData();
    }
    private void setUpListener() {
        // 添加change事件
        mViewProvince.addChangingListener(this);
        // 添加change事件
        mViewCity.addChangingListener(this);
        // 添加change事件
        mViewDistrict.addChangingListener(this);
        // 添加onclick事件

    }

    private void setUpData() {
        initProvinceDatas();
        mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(activity, mProvinceDatas));
        // 设置可见条目数量
        mViewProvince.setVisibleItems(7);
        mViewCity.setVisibleItems(7);
        mViewDistrict.setVisibleItems(7);
        updateCities();
        updateAreas();
    }

    private void init() {
        WindowManager wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        LogUtils.i("width-->" + width);
        view = LayoutInflater.from(activity).inflate(R.layout.picker_location, null);
        setContentView(view);
        tv_cancle= view.findViewById(R.id.cancle_picker);
        tv_ok= view.findViewById(R.id.ok_picker);
        mViewProvince=view.findViewById(R.id.id_province);
        mViewCity=view.findViewById(R.id.id_city);
        mViewDistrict=view.findViewById(R.id.id_district);
        tv_cancle.setOnClickListener(this);
        tv_ok.setOnClickListener(this);
        Window dialogWindow = getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.END | Gravity.BOTTOM);
        lp.width = width;
        dialogWindow.setAttributes(lp);
        
        
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.cancle_picker:
                dismiss();
                break;
            case R.id.ok_picker:
                showSelectedResult();
                dismiss();
                break;
        }
    }
    private void showSelectedResult() {
//        Toast.makeText(activity, "当前选中:"+mCurrentProviceName+","+mCurrentCityName+","
//                +mCurrentDistrictName+","+mCurrentZipCode, Toast.LENGTH_SHORT).show();
        String region=mCurrentProviceName+mCurrentCityName+mCurrentDistrictName;
        ChangeType("region",region);
//        spu.getUser().setRegion(mCurrentProviceName+mCurrentCityName+mCurrentDistrictName);
    }
    private void ChangeType(String type, String value) {
//
        Map<String, String> map = new HashMap<>();
        map.put(type, value);
        map.put("uid", spu.getUser().getUid());
        LogUtils.e("uid" + spu.getUser().getUid());
        Factory.provideHttpService().changeUser(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<UserEntity, Boolean>() {
                    @Override
                    public Boolean call(UserEntity userEntity) {
                        LogUtils.e("photo", userEntity.code);
//                        if ("200".equals(userEntity.code)) {
//
//                            return true;
//                        } else {
//                            TUtils.toast(userEntity.msg);
//                            return true;
//                        }
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<UserEntity>() {
                    @Override
                    public void call(UserEntity userEntity) {
                        if ("200".equals(userEntity.code)) {
                            TUtils.toast("修改成功");
                            spu.setUser(userEntity.data);

                        } else {
                            TUtils.toast(userEntity.msg);
                        }

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.e("throwable------" + throwable.getMessage());
                    }
                });
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        if (wheel == mViewProvince) {
            updateCities();
        } else if (wheel == mViewCity) {
            updateAreas();
        } else if (wheel == mViewDistrict) {
            mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
            mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
        }
    }
    private void updateCities() {
        int pCurrent = mViewProvince.getCurrentItem();
        mCurrentProviceName = mProvinceDatas[pCurrent];
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        if (cities == null) {
            cities = new String[] { "" };
        }
        mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(activity, cities));
        mViewCity.setCurrentItem(0);
        updateAreas();
    }
    private void updateAreas() {
        int pCurrent = mViewCity.getCurrentItem();
        mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
        String[] areas = mDistrictDatasMap.get(mCurrentCityName);

        if (areas == null) {
            areas = new String[] { "" };
        }
        mViewDistrict.setViewAdapter(new ArrayWheelAdapter<String>(activity, areas));
        mViewDistrict.setCurrentItem(0);
    }


    public void initProvinceDatas()
    {
        List<ProvinceModel> provinceList = null;
        AssetManager asset = getContext().getAssets();
        try {
            InputStream input = asset.open("province_data.xml");
            // 创建一个解析xml的工厂对象
            SAXParserFactory spf = SAXParserFactory.newInstance();
            // 解析xml
            SAXParser parser = spf.newSAXParser();
            XmlParserHandler handler = new XmlParserHandler();
            parser.parse(input, handler);
            input.close();
            // 获取解析出来的数据
            provinceList = handler.getDataList();
            //*/ 初始化默认选中的省、市、区
            if (provinceList!= null && !provinceList.isEmpty()) {
                mCurrentProviceName = provinceList.get(0).getName();
                List<CityModel> cityList = provinceList.get(0).getCityList();
                if (cityList!= null && !cityList.isEmpty()) {
                    mCurrentCityName = cityList.get(0).getName();
                    List<DistrictModel> districtList = cityList.get(0).getDistrictList();
                    mCurrentDistrictName = districtList.get(0).getName();
                    mCurrentZipCode = districtList.get(0).getZipcode();
                }
            }
            //*/
            mProvinceDatas = new String[provinceList.size()];
            for (int i=0; i< provinceList.size(); i++) {
                // 遍历所有省的数据
                mProvinceDatas[i] = provinceList.get(i).getName();
                List<CityModel> cityList = provinceList.get(i).getCityList();
                String[] cityNames = new String[cityList.size()];
                for (int j=0; j< cityList.size(); j++) {
                    // 遍历省下面的所有市的数据
                    cityNames[j] = cityList.get(j).getName();
                    List<DistrictModel> districtList = cityList.get(j).getDistrictList();
                    String[] distrinctNameArray = new String[districtList.size()];
                    DistrictModel[] distrinctArray = new DistrictModel[districtList.size()];
                    for (int k=0; k<districtList.size(); k++) {
                        // 遍历市下面所有区/县的数据
                        DistrictModel districtModel = new DistrictModel(districtList.get(k).getName(), districtList.get(k).getZipcode());
                        // 区/县对于的邮编，保存到mZipcodeDatasMap
                        mZipcodeDatasMap.put(districtList.get(k).getName(), districtList.get(k).getZipcode());
                        distrinctArray[k] = districtModel;
                        distrinctNameArray[k] = districtModel.getName();
                    }
                    // 市-区/县的数据，保存到mDistrictDatasMap
                    mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
                }
                // 省-市的数据，保存到mCitisDatasMap
                mCitisDatasMap.put(provinceList.get(i).getName(), cityNames);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {

        }
    }
    @Override
    public void dismiss() {
        super.dismiss();
        ChangeLocationEvent event = new ChangeLocationEvent();
        event.setlocationChange(true);
        EventBus.getDefault().post(event);
    }
}
